import 'dart:core';

import 'package:flutter/material.dart';

class BaseInformationRow<T> extends StatelessWidget {
  BaseInformationRow({
    Key key,
    @required this.list,
    @required this.builder,
  }) : super(key: key);

  final List<dynamic> list;

  final Widget Function(T item) builder;

  @override
  Widget build(BuildContext context) {
    return Visibility(
      visible: list.length > 0,
      child: LayoutBuilder(builder: (context, constraints) {
        double _width = (constraints.biggest.width - (5 * (list.length - 1))) / list.length;
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: list.map((item) => Container(width: _width, child: builder(item))).toList(),
        );
      }),
    );
  }
}

class BaseInformationRowItem extends StatelessWidget {
  BaseInformationRowItem({
    Key key,
    this.isAnimation = true,
    this.text,
    this.numberText,
    this.onTap,
    this.decorator,
  }) : super(key: key);

  /// 开启动画效果 要保证 numberText 能够成功转化为 num 类型
  final bool isAnimation;

  final String text;

  final String numberText;

  final Widget Function(String) decorator;

  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return this.isAnimation == true ? _buildAnimationWidget(context) : _buildNormalWidget(context, this.numberText);
  }

  Widget _buildAnimationWidget(BuildContext context) {
    try{
      num number = num.tryParse(this.numberText);
      return number == null
          ? _buildNormalWidget(context, this.numberText)
          : TweenAnimationBuilder(
        tween: Tween<num>(begin: 0, end: number ?? 0),
        duration: Duration(milliseconds: 1000),
        builder: (context, num value, widget) {
          num numberText = number.runtimeType == int ? value.floor() : value.floorToDouble();
          String text;
          if (numberText > 10000) {
            text = (numberText / 10000).toStringAsFixed(1) + '万';
          } else {
            text = numberText.toString();
          }
          return _buildNormalWidget(context, text);
        },
      );
    }catch(e){
      return Text(e.toString());
    }

  }

  Widget _buildNormalWidget(BuildContext context, String numberText) {
    return InkWell(
      onTap: this.onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          this.decorator == null ? Text(numberText, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 15)) : this.decorator(numberText),
          SizedBox(height: 4.0),
          Text(this.text ?? '', style: Theme.of(context).textTheme.subtitle2),
        ],
      ),
    );
  }
}
